# -*- coding: utf-8 -*-

from django.http import JsonResponse, QueryDict
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt 

from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination

from message.models import Message
from message.serializers import MessageSerializer
from user.models import UserProfile


class FaqsPagination(PageNumberPagination):
    '''自定义分页
    '''
    #默认每页显示的个数
    page_size = 20
    #可以动态改变每页显示的个数
    page_size_query_param = 'page_size'
    #页码参数
    page_query_param = 'page'
    #最多能显示多少页
    max_page_size = 100


class MessageListView(APIView):
    def get(self, request, format=None):
        q = Q(display="True")
        my_dict = {}
        q1 = Message.objects.filter(q).order_by('date')
        paginate = FaqsPagination()
        page_obj = paginate.paginate_queryset(q1, request)           
        serializer = MessageSerializer(page_obj, many=True)
        return JsonResponse({"count": q1.count(), "results": serializer.data})
 
 
def show_msg_num(request):
    num = Message.objects.filter(Q(display="True")).count()
    return JsonResponse({'num_msg': num}, safe=False)


@csrf_exempt 
def handle_message(request):
    if request.method == "GET":
        q1 = Message.objects.all().order_by('-date')
        serializer = MessageSerializer(q1, many=True)
        return JsonResponse({"count": q1.count(), "results": serializer.data})
    elif request.method == "PUT":
        put = QueryDict(request.body)
        username = put.get('username')
        message = put.get('message')
        user = UserProfile.objects.filter(username=username).first()
        if not message:
            return JsonResponse({'msg': '请填写留言内容！'}, safe=False)
        elif len(message) > 200:
            return JsonResponse({'msg': '留言长度请不要超过200字符！'}, safe=False)
        try:
            Message.objects.create(username=username, name=user.name, email=user.email, content=message)
        except Exception as error:
            print(error)
            return JsonResponse({'msg': '留言提交失败！'}, safe=False)
        return JsonResponse({'msg': '留言提交成功！'}, safe=False)



